package cn.szzsi._web;

import cn.szzsi.common.kit.CommonUtil;

import cn.szzsi.common.kit.IdGen;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by yuanzheng on 2016/11/7.
 */
public class WeiXinIndexAddress extends BaseWebController<Member> {
    private String appid;//微信应用id
    private String secret;//微信应用秘钥
    private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    public void index(){
        String shopId=getPara("shopId");
        //微信登录验证
        String code =getPara("code");
        SiteConfig siteConfig= SiteConfig.getByShopId(shopId);
        String shopAlias=siteConfig.getStr("shopAlias");

        setAttr("shopAlias",shopAlias);
        setAttr("shopId",shopId);
        setAttr("base", getRequest().getContextPath());
        setAttr("siteConfig",siteConfig);
        int openWeixnLogin=siteConfig.getInt("openWeixnLogin");
        if (openWeixnLogin==1) {//开启微信授权登录
            appid=siteConfig.getStr("appid");
            secret=siteConfig.getStr("secret");
            if(StrKit.isBlank(code)){//code为null
                String fansIndexUrl= CommonUtil.getBusinessWebName(siteConfig)+"/b/weiXinIndex?shopId="+shopId+"";
                String redirect_uri= null;
                try {
                    redirect_uri = URLEncoder.encode(fansIndexUrl,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String reqUrl=AUTHORIZE_URL+"?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                redirect(reqUrl);
            }else{
                //已经获取到code,根据code取access_token
                String reqUrl=ACCESS_TOKEN_URL+"?APPID="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
                String result= HttpKit.get(reqUrl);
                JSONObject obj = JSON.parseObject(result);
                String access_token=obj.getString("access_token");
                if(StrKit.notBlank(access_token)){
                    String openid = obj.getString("openid");
                    Member member= Member.dao.isExistByOpenid(openid);
                    if(member!=null){//用户名已存在,将用户的id存入session,并且存入cookie
                        setAttr("loginMember",member);
                        // 写入会员登录Session
                        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));
                        // 写入会员登录Cookie
                        Cookie loginMemberUsernameCookie = null;
                        Cookie loginTypeCookie = null;
                        try {
                            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
                            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"customer");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
                        loginTypeCookie.setPath(getRequest().getContextPath()+"/");
                        getResponse().addCookie(loginMemberUsernameCookie);
                        getResponse().addCookie(loginTypeCookie);
                    }else{//用户名未存在,拉取用户信息
                        String getUserInfo = USER_INFO_URL+"?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
                        String resultUserInfo = HttpKit.get(getUserInfo);
                        JSONObject userJson = JSON.parseObject(resultUserInfo);
                        String nickname = userJson.getString("nickname");
                        String sex = userJson.getString("sex");
                        String country = userJson.getString("country");
                        String province = userJson.getString("province");
                        String city = userJson.getString("city");
                        String headimgurl = userJson.getString("headimgurl");
                        String privilege = userJson.getString("privilege");
                        //String unionid=userJson.get("unionid");//待处理
                        String registerIp = getRequest().getRemoteAddr();
                        //保存用户信息
                        Member.saveMemberInfo("0","0",openid,nickname,sex,country,province,city,headimgurl,privilege,null,shopId,registerIp, IdGen.get().nextId(10));
                        Member saveMember= Member.dao.getByOpenid(openid);//上一步保存的信息会员
                        setAttr("loginMember",saveMember);
                        // 写入会员登录Session
                        setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, saveMember.getStr("id"));
                        // 写入会员登录Cookie
                        Cookie loginMemberUsernameCookie = null;
                        Cookie loginTypeCookie = null;
                        try {
                            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(saveMember.getStr("username").toLowerCase(), "UTF-8"));
                            loginTypeCookie=new Cookie(Member.LOGIN_TYPE_COOKIE_NAME,"customer");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        loginMemberUsernameCookie.setPath(getRequest().getContextPath() + "/");
                        loginTypeCookie.setPath(getRequest().getContextPath()+"/");
                        getResponse().addCookie(loginMemberUsernameCookie);
                        getResponse().addCookie(loginTypeCookie);
                    }
                    getTemplatePath(shopId,"fansindex.html");
                }else{
                    render("/html/404.html");
                }

            }
        }else{
            getTemplatePath(shopId,"fansindex.html");
        }

        }
    }
